<script setup lang="ts">
import { ref, onMounted, reactive } from 'vue'
import { i18n } from 'boot/i18n'
import { Notify } from 'quasar'
import api from 'src/api'
import type { MeetingUser, MeetingUserUpdate } from 'src/api/service'

const tc = i18n.global.tc

// 个人信息 (从 API 获取)
const userInfo = ref<MeetingUser | null>(null)
const loadingUserInfo = ref(false)
const savingUserInfo = ref(false)

// 用于编辑的个人信息
const editableUserInfo = reactive({
  fullname: '',
  telephone: '',
  company: ''
})

// 获取个人信息
const fetchUserInfo = async () => {
  loadingUserInfo.value = true
  try {
    const response = await api.service.txMeeting.getPersonalMeetingUserInfo()
    userInfo.value = response.data

    // 初始化可编辑信息
    if (userInfo.value) {
      editableUserInfo.fullname = userInfo.value.user.fullname
      editableUserInfo.telephone = userInfo.value.user.telephone
      editableUserInfo.company = userInfo.value.user.company
    }
  } catch (error) {
    console.error('Error fetching personal info:', error)
    Notify.create({
      message: tc('获取个人信息失败'),
      type: 'negative',
      icon: 'error',
      position: 'top'
    })
  } finally {
    loadingUserInfo.value = false
  }
}

// 保存个人信息
const saveUserInfo = async () => {
  if (!userInfo.value) return

  savingUserInfo.value = true
  try {
    // 处理姓名：判断是拼音文字(有空格)还是字形文字
    let firstName = ''
    let lastName = ''

    if (editableUserInfo.fullname.includes(' ')) {
      // 拼音文字（如：John Doe）- 用空格分隔
      const nameParts = editableUserInfo.fullname.split(' ')
      firstName = nameParts[0] || ''
      lastName = nameParts.slice(1).join(' ') || ''
    } else {
      // 字形文字（如：张三）- 第一个字作为姓
      lastName = editableUserInfo.fullname.charAt(0) || ''
      firstName = editableUserInfo.fullname.substring(1) || ''
    }

    const payload: MeetingUserUpdate = {
      telephone: editableUserInfo.telephone,
      company: editableUserInfo.company,
      first_name: firstName,
      last_name: lastName
    }

    const response = await api.service.txMeeting.updateMeetingUser(userInfo.value.id, payload)
    userInfo.value = response.data

    Notify.create({
      message: tc('个人信息更新成功'),
      type: 'positive',
      icon: 'check_circle',
      position: 'top'
    })
  } catch (error) {
    console.error('Error updating personal info:', error)
    Notify.create({
      message: tc('更新个人信息失败'),
      type: 'negative',
      icon: 'error',
      position: 'top'
    })
  } finally {
    savingUserInfo.value = false
  }
}

// 组件挂载时获取信息
onMounted(() => {
  fetchUserInfo()
})

</script>

<template>
  <q-scroll-area style="height: calc(100vh - 50px)">
    <div class="q-pa-md">
      <h5 class="q-mt-none q-mb-md">{{ tc('个人设置') }}</h5>

      <!-- 个人信息区域 -->
      <q-card class="q-mb-md">
        <!-- <q-card-section>
          <div class="text-h6">{{ tc('个人信息') }}</div>
        </q-card-section> -->

        <q-card-section v-if="loadingUserInfo">
          <q-skeleton type="QInput" />
          <q-skeleton type="QInput" class="q-mt-sm" />
          <q-skeleton type="QInput" class="q-mt-sm" />
        </q-card-section>
        <q-card-section v-else-if="userInfo">
          <q-form @submit.prevent="saveUserInfo">
            <div class="row q-col-gutter-md">
              <div class="col-12 col-md-6">
                <div class="text-subtitle2 q-mb-sm">{{ tc('个人信息') }}</div>

                <!-- 姓名 -->
                <q-input v-model="editableUserInfo.fullname" :label="tc('姓名')" outlined dense class="q-mb-md" />

                <!-- 手机号 -->
                <q-input v-model="editableUserInfo.telephone" :label="tc('电话')" outlined dense class="q-mb-md" />

                <!-- 单位 -->
                <q-input v-model="editableUserInfo.company" :label="tc('单位')" outlined dense />
              </div>

              <div class="col-12 col-md-6">
                <div class="text-subtitle2 q-mb-sm">{{ tc('账户信息') }}</div>

                <!-- 邮箱 (用户名) -->
                <q-input :model-value="userInfo.user.username" :label="tc('邮箱') + ' (' + tc('用户名') + ')'" outlined dense
                  readonly class="q-mb-md" />

                <!-- 角色 -->
                <q-field :label="tc('会议预定角色')" stack-label outlined dense readonly class="q-mb-md">
                  <template v-slot:control>
                    <q-chip :color="userInfo.role === 'admin' ? 'orange' : 'primary'" text-color="white" dense
                      size="sm">
                      {{ userInfo.role === 'admin' ? tc('管理员') : tc('普通用户') }}
                    </q-chip>
                  </template>
                </q-field>

                <!-- 状态 -->
                <q-field :label="tc('会议预定状态')" stack-label outlined dense readonly>
                  <template v-slot:control>
                    <q-chip :color="userInfo.status === 'active' ? 'positive' : 'grey'" text-color="white" dense
                      size="sm">
                      {{ userInfo.status === 'active' ? tc('有效') : tc('无效') }}
                    </q-chip>
                  </template>
                </q-field>
              </div>
            </div>
          </q-form>
        </q-card-section>
        <q-card-section v-else>
          {{ tc('无法加载个人信息') }}
        </q-card-section>

        <q-card-actions align="right" v-if="userInfo">
          <q-btn :label="tc('保存修改')" color="primary" :loading="savingUserInfo" @click="saveUserInfo" />
        </q-card-actions>
      </q-card>

    </div>
  </q-scroll-area>
</template>
